<template>
    <div id="Map">
        <dv-border-box-1>
            <div id="container"></div>
        </dv-border-box-1>
        <!-- <div id="container"></div> -->
        <div id="res"  style=" overflow-y:auto; overflow-x:auto;"></div>
        <div class="info">
            <h4 id='status'></h4>
            <p id='result'></p>
        </div>
        <el-button type="success" @click="addMarker">添加标记</el-button>
        <el-button type="success" @click="Dingwei">非精准定位</el-button>
        <el-button type="success" @click="getOneNet">精准定位</el-button>
        <el-button type="success" @click="newPosit">实时追踪</el-button>
        <el-button type="success" @click="destoryPOsit">停止追踪</el-button>
        <el-button type="success" @click="getAddr">获取位置</el-button>
        <el-button type="success" @click="getAllAddr">历史经纬度查询</el-button>
        打开蜂鸣器<el-switch v-model="beep" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0" @change="sendBeep(data)"></el-switch>
       <!--

        <el-button type="success" @click="routeTurn">数据检测跳转</el-button>
       -->
        
        <div id="ChaXun">
            <el-descriptions class="margin-top" title="路径查询" :column="3" >
                <template slot="extra">
                  <el-button type="primary" @click="addDriving()">查询路径</el-button>
                  <el-button type="primary" @click="destoryDrive()">消除路径</el-button>
                </template>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    起始地
                  </template>
                  <el-input v-model="routeLine[0]['keyword']" placeholder="请输入内容"></el-input>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-mobile-phone"></i>
                    起始地城市
                  </template>
                  <el-input v-model="routeLine[0]['city']" placeholder="请输入内容"></el-input>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-location-outline"></i>
                    目的地
                  </template>
                  <el-input v-model="routeLine[1]['keyword']" placeholder="请输入内容"></el-input>
                </el-descriptions-item>
              </el-descriptions>
        </div>
        <div id="infomation">
            <el-button type="success" @click="changeInfo">修改信息</el-button>
            <el-descriptions title="用户信息">
                <el-descriptions-item label="用户名">
                    <el-input  placeholder="" v-model="user" :disabled="true">{{this.user}}</el-input>
                </el-descriptions-item>
                <el-descriptions-item label="密码">
                    <el-input v-model="pwd" placeholder="">{{this.pwd}}</el-input>
                </el-descriptions-item>
                <el-descriptions-item label="API-KEY">
                    <el-input  placeholder="" v-model="APIKey" :disabled="true">{{this.APIKey}}</el-input>
                </el-descriptions-item>
                <el-descriptions-item label="access-id">
                    <el-input  placeholder="" v-model="accessId" :disabled="true">{{this.accessId}}</el-input>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                    <el-input v-model="Email" placeholder="">{{this.Email}}</el-input>
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                    <el-input v-model="phone" placeholder="">{{this.phone}}</el-input>
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <div class="addr">
            <el-table :data="addrData" stripe style="width: 100%">
                <el-table-column prop="0" label="经度" width="100"></el-table-column>
                <el-table-column prop="1" label="纬度" width="100"></el-table-column>
                <el-table-column label="标记" width="100">
                    <template slot-scope="scope">
                        <el-button type="primary" size="small" @click="addMarkerThis(scope.row)">添加标记</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>
<script>
  import AMapLoader from '@amap/amap-jsapi-loader';
  //import MapLoader from '../unti/unti.js'
  export default {
    //name: 'index',
    data () {
      return {
            map: null,
            driving: null,
            geolocation:null,
            marker:null,
            geocoder:null,
            posit:[],
            adds:"",
            jing:"",
            wei:"",
            Tim:"",
            infoShow:"flase",
            marker_data:{
                jing:"114.544827",
                wei:"36.625579"
            },
            addrData:[],
            routeLine:[
                {
                    keyword:"水泵厂",
                    city:"邯郸"
                },
                {
                    keyword:"邯郸火车站",
                    // city:""
                }
            ],
            "user":"0",
            "pwd":"0",
            "APIKey":"0",
            "accessId":"0",
            "Email":"0",
            "phone":"0",
            "user_id":"",
            "infomation":[],
            beep:"",
            data:"value",
        }
    },
    mounted () {//页面创建完成后立即调用
        this.infomation = this.$route.query
        this.user_id=this.infomation[0]
        this.user = this.infomation[1]
        this.pwd = this.infomation[2]
        this.APIKey = this.infomation[3]
        this.accessId = this.infomation[5]
        this.Email = this.infomation[6]
        this.phone = this.infomation[7]
        this.initMap();
        //this.addMarker();
        //this.addDriving();
        
    },
    methods: {//用时才用
        initMap(){
            AMapLoader.load({
            securityJsCode:'cebac2d3ff9a4bd6eb66f5b7b533e872',
            key:"	5bf9a9479043cba8c98b607c629c7e18",             // 申请好的Web端开发者Key，首次调用 load 时必填
            version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins:['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation','AMap.Driving','AMap.Marker','AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap)=>{
                this.map = new window.AMap.Map("container",{  //设置地图容器id
                    viewMode:"3D",    //是否为3D地图模式
                    zoom:10,           //初始化地图级别
                    center:[114.48,36.60], //初始化地图中心点位置
                });
                this.map.addControl(new AMap.Scale())
                this.map.addControl(new AMap.ToolBar())
                this.map.addControl(new AMap.HawkEye())
                this.map.addControl(new AMap.MapType())
                this.map.addControl(new AMap.Geolocation())  
                this.map.addControl(new AMap.Driving())     
                this.map.addControl(new AMap.Marker())        
                this.map.addControl(new Amap.Geocoder())
            }).catch(e=>{
                console.log(e);
            })
        },
        addDriving(){
            console.log(this.routeLine)
            this.map.plugin('AMap.Driving',()=>{
                    this.driving = new AMap.Driving({
                        map:this.map,
                        panel:"res"
                    })
                    this.driving.search([{keyword: this.routeLine[0]["keyword"]},{keyword: this.routeLine[1]["keyword"]}],function(status,result){//[{keyword:'火车站',city:"邯郸"},{keyword:'壶口瀑布'}]
                        console.log("----------------------------")
                        console.log(status)
                        console.log(result)
                    })
                }) 
        },
        destoryDrive(){
            this.driving.clear()
        },
        addMarker() {
            console.log("jing:"+this.marker_data["jing"]+"wei:"+this.marker_data["wei"])

            if(this.marker){
                this.map.remove(this.marker)
                console.log("已删除上次的标记")
            }
            this.marker = new AMap.Marker({
                position: new AMap.LngLat(this.marker_data["jing"],this.marker_data["wei"]),
                title:"我的位置"
            });
            this.map.add(this.marker);
        },
    //精准定位
        Dingwei(){
            const that = this;
            this.map.plugin('AMap.Geolocation',()=>{
                this.geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：5s
                    buttonPosition:'RB',    //定位按钮的停靠位置
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                });
                this.map.addControl(this.geolocation);
                this.geolocation.getCurrentPosition(function(status,result){
                    console.log(status)
                    console.log(result)
                    if(status=='complete'){
                        //*****************
                        document.getElementById('status').innerHTML='定位成功'
                        var str = [];
                        str.push('定位结果：' + result.position);
                        str.push('定位类别：' + result.location_type);
                        if(result.accuracy){
                            str.push('精度：' + result.accuracy + ' 米');
                        }//如为IP精确定位结果则没有精度信息
                        str.push('是否经过偏移：' + (result.isConverted ? '是' : '否'));
                        document.getElementById('result').innerHTML = str.join('<br>');
                        //*****************
                        that.marker_data["jing"] = result.position["lng"]
                        that.marker_data["wei"] = result.position["lat"]
                        // console.log("result.position:"+result.position["lat"]);
                    }else{
                        document.getElementById('status').innerHTML='定位失败'
                        document.getElementById('result').innerHTML = '失败原因排查信息:'+result.message;
                    }
                });
            });
        },
        //逆地理编码
        getAddr(){
            const that =this
            this.getOneNet()//获取当前经纬度
            this.geocoder = new AMap.Geocoder({
                city:"010", //城市
                radius:1000 //范围
            })
            this.geocoder.getAddress([this.marker_data["jing"],this.marker_data["wei"]],(status,result)=>{
                if (status === 'complete'&&result.regeocode) {
                    var address = result.regeocode.formattedAddress;
                    console.log(address)
                    that.routeLine[0]['keyword'] = address
                }else{
                   console.log('根据经纬度查询地址失败')
                }
            })
        },
        getAllAddr(){
            this.axios({
                method:'POST',
                url:'http://192.168.1.7:5001/getAllAddr',
                data :{
                "user_id":this.user_id,
                },
                headers:{
                    'Content-Type': 'application/json' //以json格式传输
                }
            })
            .then((res)=>{
                console.log(res.data.length)
                for(var i=0;i<res.data.length;i++){
                    res.data[i][0] = parseInt(res.data[i][0]/100)+(res.data[i][0]/100-parseInt(res.data[i][0]/100))/60*100
                    res.data[i][1] = parseInt(res.data[i][1]/100)+(res.data[i][1]/100-parseInt(res.data[i][1]/100))/60*100
                }
                console.log(res.data)
                this.addrData = res.data

            })
        },
        //获取onenet 数据(GPS 经纬度)
        getOneNet(){
            const that = this
            this.axios({
            method : 'POST',
            url : 'http://192.168.1.7:5001/getOneNet ',
            data :{
                "user_id":this.user_id,
                "deviceIds" : this.accessId,
                "APIKeys" : this.APIKey,
            },
            headers:{
               // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' ,//以表单格式传输
                'Content-Type': 'application/json' //以json格式传输
            }
            })
            .then((res)=>{
                console.log(res.data);
                var wei = res.data[5]["current_value"];
                var jing = res.data[4]["current_value"];
                jing = parseInt(jing/100)+(jing/100-parseInt(jing/100))/60*100
                wei = parseInt(wei/100)+(wei/100-parseInt(wei/100))/60*100
                that.marker_data["jing"] = jing;
                that.marker_data["wei"] = wei;
                console.log("wei_:"+wei+"=="+"jing_:"+jing)
            })
            .catch((error)=>{
                console.log(error);
            })
        },
        sendBeep(res){
            console.log(res);
            this.axios({
                url:'/onenet/cmds?device_id=755493629&qos=1&timeout=30',//http://api.heclouds.com/cmds?device_id=755493629&qos=1&timeout=30
                method:'POST',
                headers:{
					//'Content-Type':"text/plain",
                    'Content-Type': 'application/x-www-form-urlencoded',
					'api-key':this.APIKey,
				},
                data:{
                    'beep':this.beep
                },
                transformRequest: [function (data) {
                // Do whatever you want to transform the data
                let ret = ''
                for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) 
                }
                return ret
            }],
            })
            .then((res)=>{
                console.log(res.data)
            })
            .catch((error)=>{
                console.log(error)
            })
        },
        //实时刷新位置
        newPosit(){
            alert("已开启实时追踪")
            this.Tim=setInterval(()=>{
                this.getOneNet();
                this.addMarker();
                this.destoryDrive();
                this.addDriving();
            },5000)
        },
        destoryPOsit(){
            if(this.Tim){
                clearInterval(this.Tim)
            } 
            alert("已停止追踪")
        },
        routeTurn(){
           // this.$router.push({ name:'Index', query:{ name:'word', age:'11' } })
           this.$router.push({ name:'Data'})
        },
        changeInfo(){
            const that = this
            this.axios({
            method : 'POST',
            url : 'http://192.168.1.7:5001/changeInfo ',
            data :{
                user : this.user,
                psw : this.pwd,
                Email : this.Email,
                phone : this.phone
            },
            headers:{
                'Content-Type': 'application/json' //以json格式传输
            }
            })
            .then((res)=>{
               console.log(res)
               this.$message({
                message: '修改信息成功',
                type: 'success'
              });
            })
            .catch((error)=>{
                console.log(error);
            })
        },
        addMarkerThis(data){
            console.log(data)
            this.marker_data["jing"] = data[0]
            this.marker_data["wei"] = data[1]
            this.addMarker();
        }

    }   
}
  </script>
  <style scoped>
    #Map{
        background: url(./bg.jpeg);
    }
    #container{
        padding:0px;
        margin: 0px;
        margin: 0 auto;
        width: 50%;
        height: 400px;
    }
    .startEnd{
        width: 100px;
        height: 35px;
    }
    #chaXun{
        width: 450px;
        height: auto;
        border: rgb(9, 4, 4) solid 1px;
    }
    #res{
        width: 350px;
        height: 360px;
        /* border: rgb(9, 4, 4) solid 1px; */
        position: absolute;
        top: 30px;
        left: 22px;
    }
    .info{
        width: 300px;
        height: auto;
        position: absolute;
        top: 0px;
        right: 0px; 
    }
    #infomation{
        background-color: rgb(246, 246, 248);
        /* top:800px; */
        width: 100%;
        height: 180px;
    }
    .addr{
        width: 300px;
        height: 300px;
        position: absolute;
        left: 1200px;
        top:  105px;
        overflow:auto;
    }
    /* #margin-top{
        
    } */
  </style>
  


